package com.xiaolv.web.controller;

import com.xiaolv.web.model.Order;
import com.xiaolv.web.service.OrderService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 订单数据表测试
 */
@Controller
@RequestMapping(value = "/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * mybatis xml添加
     *
     * @return
     * @throws Exception
     */
    @ResponseBody
    @GetMapping(value = "add")
    public Boolean add() throws Exception {
        Order o = new Order();
        o.setUserId(2);
        o.setStatus("3");
        //Calendar cal = Calendar.getInstance();
        //cal.add(Calendar.MONTH, -1);
        o.setOrderDate(LocalDate.now());
        orderService.add(o);
        return true;
    }

    /**
     * mybatis plus添加
     *
     * @return
     * @throws Exception
     */
    @ResponseBody
    @GetMapping(value = "add2")
    public Boolean add2() {
        Order o = new Order();
        o.setUserId(2);
        o.setStatus("5");
        //往前一个月表里添加数据
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, -1);
        o.setOrderDate(DateToLocaleDate(cal.getTime()));
        orderService.save(o);
        return true;
    }

    @ResponseBody
    @GetMapping(value = "list")
    public List<Order> list() {

        //查询所有表
        List<Order> list = orderService.list();

        //查询两张表的数据，2个月
        List<Order> list2 = orderService.list(Wrappers.<Order>lambdaQuery()
                .between(Order::getOrderDate, "2020-09-01", "2020-10-31"));

        //查询指定表的数据，一张表
        List<Order> list3 = orderService.list(Wrappers.<Order>lambdaQuery()
                .eq(Order::getOrderDate, "2020-10-09"));

        return list;
    }

    /**
     * date转localDate
     *
     * @param date
     * @return
     */
    public static LocalDate DateToLocaleDate(Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        return instant.atZone(zoneId).toLocalDate();
    }
}
